package com.tbit.uqbike.webmanager.util;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间工具类
 *
 * @author jing
 */
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYY_MM_DD_HH = "yyyy-MM-dd HH";

    public static String HH = "HH";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
    private static DateTimeFormatter YearMonthDay_Time = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter YearMonthDay_ = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差
     */
    public static Long getDateDiff(Date endDate, Date nowDate) {
        return endDate.getTime() - nowDate.getTime();
    }

    /**
     * 获取指定时间段内每一天的日期
     */
    public static List<String> findDaysStr(String startTime, String endTime) {
        return findDaysStr(startTime, endTime, Calendar.DAY_OF_MONTH);
    }

    public static List<String> findDaysStr(String startTime, String endTime, int timeUtil) {
        return findDaysStr(startTime, endTime, timeUtil, YYYY_MM_DD);

    }

    public static List<String> findDaysStr(Object startTime, Object endTime, int timeUtil, String format) {
        List<String> daysStrList = new ArrayList<>();
        Calendar calBegin = Calendar.getInstance();
        Calendar calEnd = Calendar.getInstance();
        Date dBegin = parseDate(startTime);
        Date dEnd = parseDate(endTime);
        daysStrList.add(parseDateToStr(format, dBegin));
        calBegin.setTime(dBegin);
        calEnd.setTime(dEnd);
        while (dEnd.after(calBegin.getTime())) {
            calBegin.add(timeUtil, 1);
            String dayStr = parseDateToStr(format, calBegin.getTime());
            daysStrList.add(dayStr);
        }
        return daysStrList;

    }

    /**
     * 指定日期加天数
     */
    public static Date addTime(Object dateTime, int days) {
        return addTime(dateTime, Calendar.DAY_OF_MONTH, days);
    }

    public static Date addTime(Object dateTime, int timeUtil, int time) {
        Calendar calender = Calendar.getInstance();
        calender.setTime(parseDate(dateTime));
        calender.add(timeUtil, time);
        return calender.getTime();
    }

    /**
     * 两个时间差是否三个月
     */
    public static boolean MoreThenMonth(Date date, Date date2, Integer month) {
        boolean result = false;
        month = month * 2628000;
        if (date.getTime() / 1000 - date2.getTime() / 1000 > month) {//相差的时间不能大于三个月
            result = true;
        }
        return result;
    }

    public static Integer toYYYYMMDDInt(Date date) {
        String timeStr = parseDateToStr("yyyyMMdd", date);
        return Integer.parseInt(timeStr);
    }

    public static Date endOfDay(Date date) {
        return DateUtil.endOfDay(date);
    }

    /**
     * 日期转字符串类型
     */
    public static String DateToString(Date d) {
        return YearMonthDay_Time.format(d.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
    }

    //获取某段时间内的所有日期
    public static List<String> findDates(Date dStart, Date dEnd) {
        String start = DateToString(dStart);
        String end = DateToString(dEnd);
        List<String> dateList = new LinkedList<>();
        try {
            Calendar cStart = Calendar.getInstance();
            cStart.setTime(Date.from(LocalDate.parse(start, YearMonthDay_Time).atStartOfDay(ZoneId.systemDefault()).toInstant()));
            dateList.add(YearMonthDay_.format(cStart.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));
            while (LocalDate.parse(end, YearMonthDay_Time).isAfter(cStart.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
                cStart.add(Calendar.DAY_OF_MONTH, 1);
                dateList.add(YearMonthDay_.format(cStart.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return dateList;
    }

    /**
     * 根据时间获取当前整点时间
     * 如果传入时间不是今天则返回入参
     *
     * @param inputDate 查询日期
     * @return date
     */
    public static Date getDayOnTheHour(Date inputDate) {
        String inputDateStr = DateUtil.formatDate(inputDate);
        String today = DateUtil.today();
        if (Objects.equals(inputDateStr, today)) {
            //查询当前整点的数据
            LocalDateTime localDateTime = LocalDateTime.now()
                    .withHour(DateUtil.thisHour(true))
                    .withMinute(0).withSecond(0).withNano(0);
            return DateUtil.date(localDateTime);
        }
        return DateUtil.parseDateTime(inputDateStr + " 23:59:59");
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(MoreThenMonth(new Date(), formatter.parse("2021-10-15 20:28:23"), 2));
        System.out.println(toYYYYMMDDInt(new Date()));
    }
}
